package com.ruoyi.framework.security.service;

import javax.annotation.Resource;

import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.system.domain.CollegeStaff;
import com.ruoyi.project.system.domain.Member;
import com.ruoyi.project.system.domain.Student;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.CollegeStaffMapper;
import com.ruoyi.project.system.mapper.MemberMapper;
import com.ruoyi.project.system.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.LoginUser;

import java.util.List;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private CollegeStaffMapper collegeStaffMapper;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }


        if(username.equals("admin")){

                // 用户验证
                Authentication authentication = null;
                try
                {
                    // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                    authentication = authenticationManager
                            .authenticate(new UsernamePasswordAuthenticationToken(username, password));
                }
                catch (Exception e)
                {
                    if (e instanceof BadCredentialsException)
                    {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                        throw new UserPasswordNotMatchException();
                    }
                    else
                    {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                        throw new CustomException(e.getMessage());
                    }
                }
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                // 生成token
                return tokenService.createToken(loginUser);
        }else{

                List<Member> member = memberMapper.setMemberList(username,password);

                if(member.size()>1){
                    throw new UsernameNotFoundException("用户名密码重复，请找学校管理员处理");
                }

                if (StringUtils.isNull(member))
                {
                    throw new UsernameNotFoundException("登录用户不存在或密码错误");
                }else{
                    CollegeStaff coll = collegeStaffMapper.selectCollegeByMeberId(member.get(0).getId());
                    if(member.get(0).getTypeCode().intValue()==2){
                        username="老师";
                        password="123456";
                    }else if(member.get(0).getTypeCode().intValue()==3){
                        username="新华";
                        password="123456";
                    }

                    // 用户验证
                    Authentication authentication = null;
                    try
                    {
                        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                        authentication = authenticationManager
                                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
                    }
                    catch (Exception e)
                    {
                        if (e instanceof BadCredentialsException)
                        {
                            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                            throw new UserPasswordNotMatchException();
                        }
                        else
                        {
                            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                            throw new CustomException(e.getMessage());
                        }
                    }
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
                    LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                    loginUser.setCollegeStaff(coll);
                    // 生成token
                    return tokenService.createToken(loginUser);

            }

        }

    }


    /**
     * 微信端登录登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param type 1:学生   2 老师
     * @return 结果
     */
    public String wxLogin(String username, String password,int type) {

        if (type == 1) {

            //学生登录
            List<Student> student =  studentMapper.selectStudentByUserIdcard(username);
            if(student.size() ==0){
                throw new UsernameNotFoundException("登录用户不存在");
            }
            if(student.size() > 1){
                throw new UsernameNotFoundException("身份证重复，请找学校管理员处理");
            }
            if(student.get(0) == null){
                throw new UsernameNotFoundException("登录用户不存在或密码错误");
            }

            if(!student.get(0).getRealName().equals(password)){
                throw new UsernameNotFoundException("登录用户不存在或密码错误");
            }

            username="学生";
            password="123456";
            // 用户验证
            Authentication authentication = null;
            try
            {
                // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager
                        .authenticate(new UsernamePasswordAuthenticationToken(username, password));
            }
            catch (Exception e)
            {
                if (e instanceof BadCredentialsException)
                {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                    throw new UserPasswordNotMatchException();
                }
                else
                {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                    throw new CustomException(e.getMessage());
                }
            }
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();

            loginUser.setStudent(student.get(0));
            // 生成token
            return tokenService.createToken(loginUser);


        } else if (type == 2) {
            //老师登录
            List<Member> member = memberMapper.setMemberList(username,password);

            if(member.size() ==0){
                throw new UsernameNotFoundException("登录用户不存在");
            }

            if(member.size()>1){
                throw new UsernameNotFoundException("用户名密码重复，请找学校管理员处理");
            }

            if (StringUtils.isNull(member.get(0))) {
                throw new UsernameNotFoundException("登录用户不存在或密码错误");
            } else {
                CollegeStaff coll = collegeStaffMapper.selectCollegeByMeberId(member.get(0).getId());

                    username = "老师";
                    password = "123456";


                // 用户验证
                Authentication authentication = null;
                try {
                    // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                    authentication = authenticationManager
                            .authenticate(new UsernamePasswordAuthenticationToken(username, password));
                } catch (Exception e) {
                    if (e instanceof BadCredentialsException) {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                        throw new UserPasswordNotMatchException();
                    } else {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                        throw new CustomException(e.getMessage());
                    }
                }
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                loginUser.setCollegeStaff(coll);
                // 生成token
                return tokenService.createToken(loginUser);

            }

        }
        return null;
    }
}
